package wec_wallet.ebo.com.activity.register;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import bassproject.ebo.com.ebobass.http_utils.utils.LoadingUtils;
import bassproject.ebo.com.ebobass.http_utils.utils.NetState;
import wec_wallet.ebo.com.utils.URLs;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import bassproject.ebo.com.ebobass.utils.StringUtil;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.bean.BeanManager;
import wec_wallet.ebo.com.utils.Functions;

public class SignActivity extends MyBaseActivity {
    @BindView(R.id.spinner_area_number)
    Spinner spinner_area_number;
    @BindView(R.id.actionbar_back)
    RelativeLayout actionbar_back;
    @BindView(R.id.btn_ok)
    Button btn_ok;
    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.et_phonecode)
    EditText et_phonecode;
    @BindView(R.id.btn_get_code_phone)
    Button btn_get_code_phone;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.et_rep_password)
    EditText et_rep_password;
    @BindView(R.id.tv_agreement)
    TextView tv_agreement;
    @BindView(R.id.cb_selector)
    CheckBox cb_selector;

    Handler mhandle_getcode_phone = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    Integer v = (Integer) msg.obj;
                    if (v > 0) {
                        sendMessageDelayed(obtainMessage(1, v - 1), 1000);
                        btn_get_code_phone.setText(v.toString() + "s");
                    } else {
                        btn_get_code_phone.setClickable(true);
                        btn_get_code_phone.setText(getResources().getString(R.string.get_phone_code_send));
                    }
                    break;
            }
        }
    };
    String phone, code, password, password_rep, ip;
    private String prefix;
    Handler handlerSign = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    sendSign();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    public void initViews() {
        if (BeanManager.areaNumber == null) {
            Functions.getPhonePrefix(this, new ListenerGet_Phone_Prefix());
        } else {
            setSpinner();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onClick_Back();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
    }

    //返回键
    @OnClick(R.id.actionbar_back)
    void onClick_Back() {
        Intent intent = new Intent();
        intent.setClass(SignActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    //获取验证码
    @OnClick(R.id.btn_get_code_phone)
    void clickGetCode() {
        String phone = et_username.getText().toString();
        Map<String, Object> postParams;
        //手机号是否为空
        if (phone == null || TextUtils.isEmpty(phone)) {
            IToast.show(getResources().getString(R.string.login_hint_input_username));
            return;
        }
        //获取验证码
        postParams = new HashMap<String, Object>();
//        postParams.put("lan", I_Share.getLanguageType_String());
        postParams.put("mobile", phone);
        postParams.put("prefix", prefix);
        Functions.post(this, URLs.GET_MOBILE_CODE, postParams, new ListenerGetCode_Phone(), true, true);
    }

    //注册
    @OnClick(R.id.btn_ok)
    void onClick_OK() {
        //手机号是否为空
        phone = et_username.getText().toString();
        if (StringUtil.isEmpty(phone)) {
            show_Toast(getResources().getString(R.string.login_hint_input_username));
            return;
        }
        //验证码是否为空
        code = et_phonecode.getText().toString();
        if (StringUtil.isEmpty(code)) {
            show_Toast(getResources().getString(R.string.login_hint_input_phone_code));
            return;
        }
        //密码是否为空
        password = et_password.getText().toString();
        if (StringUtil.isEmpty(password)) {
            show_Toast(getResources().getString(R.string.login_hint_input_password));
            return;
        }
        //重复密码是否为空
        password_rep = et_rep_password.getText().toString();
        if (StringUtil.isEmpty(password_rep)) {
            show_Toast(getResources().getString(R.string.login_hint_input_password_rep));
            return;
        }
        //是否同意用户协议
        if(!cb_selector.isChecked()){
            show_Toast(getResources().getString(R.string.hint_agreement_checked));
            return;
        }
        LoadingUtils.progressDialogShow(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                ip = NetState.getNetIp();
                handlerSign.sendEmptyMessage(1);
            }
        }).start();


    }

    //用户协议界面
    @OnClick(R.id.tv_agreement)
    void onClickAgreement() {
        startActivity(new Intent().setClass(this, AgreementActivity.class));
    }

    private void sendSign() {
        Map postParams = new HashMap<String, Object>();
        postParams.put("ip", ip);
        postParams.put("prefix", prefix);
        postParams.put("mobile", phone);
        postParams.put("code", code);
        postParams.put("password", password);
        postParams.put("password_confirmation", password_rep);
        Functions.post(this, URLs.SIGN, postParams, new ListenerSign(phone, password), true, true);
    }


    //接口返回 start======================================================================================================================

    private void setSpinner() {
        //适配器
        ArrayAdapter arrAdapter = new ArrayAdapter<String>(this, R.layout.login_spinner_item, BeanManager.areaNumber.getNumbers());
        //设置样式
        arrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器

        spinner_area_number.setAdapter(arrAdapter);
        spinner_area_number.setSelection(BeanManager.areaNumber.getNumbers().size() - 1, true);
        spinner_area_number.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                                          @Override
                                                          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                                              prefix = spinner_area_number.getSelectedItem().toString().substring(1);
                                                              Log.d("LGY", "prefix=" + prefix);
                                                          }

                                                          @Override
                                                          public void onNothingSelected(AdapterView<?> parent) {

                                                          }
                                                      }
        );
        spinner_area_number.setSelection(0);
    }

    //注册
    class ListenerSign implements IHttpPostListener {
        String phone, password;

        public ListenerSign(String _phone, String _password) {
            phone = _phone;
            password = _password;
        }

        @Override
        public void responseSuccess(String result) {
            Lg.d("注册 result=" + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }
                    if (error == 0) {
                        String userid = resultObject.getString("id");
                        String token = resultObject.getString("remember_token");
                        String nickname = resultObject.getString("nickname");
                        String avatar_path = resultObject.getString("avatar_path");//头像地址
                        String avatar = resultObject.getString("avatar");//头像文件夹
                        String name = resultObject.getString("name");
                        //成功
                        I_Share.saveAccount(phone, null, password, token, userid);
                        I_Share.setAvatar(avatar_path + avatar);
                        I_Share.setNickname(nickname);
                        I_Share.setIsLogin(true);
                        Functions.startMainActivity(SignActivity.this);
                        finish();
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
                LoadingUtils.progressDialogDismiss();
            }
        }

        @Override
        public void onTimeOut() {
            LoadingUtils.progressDialogDismiss();
        }
    }

    //获取手机验证码
    class ListenerGetCode_Phone implements IHttpPostListener {
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("获取手机验证码 result=" + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }
                    if (error == 0) {
                        IToast.show(getResources().getString(R.string.get_phone_code_success));
                        //成功
                        btn_get_code_phone.setClickable(false);
                        mhandle_getcode_phone.sendMessage(mhandle_getcode_phone.obtainMessage(1, getResources().getInteger(R.integer.resend_smscode)));
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            }
        }

        @Override
        public void onTimeOut() {

        }
    }

    //接口返回 end======================================================================================================================

    //获取手机区号
    class ListenerGet_Phone_Prefix implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("获取手机区号 result=" + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }

                    if (error == 0) {
                        //成功
                        JSONArray jsonArray = new JSONArray(resultObject.getString("data"));
                        List<String> list = new ArrayList<String>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            list.add("+" + jsonArray.getJSONObject(i).getString("prefix"));
                            Lg.d("list " + i + " = " + list.get(i));
                        }
                        BeanManager.initAreaNumber(list);
                        setSpinner();
                    }

                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            }
        }
    }
}
